package com.cloud.freeflow.api.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cloud.freeflow.api.entity.BizType;
import com.cloud.freeflow.api.entity.ProcDef;
import com.cloud.freeflow.api.mapper.BizTypeMapper;
import com.cloud.freeflow.api.mapper.ProcDefMapper;
import com.cloud.freeflow.api.service.BizTypeService;

import tk.mybatis.mapper.entity.Example;

@Service
@Transactional
public class BizTypeServiceImpl implements BizTypeService {

	@Autowired
	private BizTypeMapper bizTypeMapper;

	@Autowired
	private ProcDefMapper procDefMapper;

	@Override
	public List<BizType> listAll() {
		Example example = new Example(BizType.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andNotEqualTo("deleteFlag", 1);
		return bizTypeMapper.selectByExample(example);
	}

	@Override
	public long delete(long bizId) {
		BizType bizType = new BizType();
		bizType.setBizId(bizId);
		bizType.setDeleteFlag(1);
		bizTypeMapper.updateByPrimaryKeySelective(bizType);

		ProcDef procDef = new ProcDef();
		procDef.setDeleteFlag(1);
		Example example = new Example(ProcDef.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andEqualTo("bizId", bizId);
		procDefMapper.updateByExampleSelective(procDef, example);
		return bizId;
	}

	@Override
	public BizType update(BizType bizType) {
		BizType oldBizType = bizTypeMapper.selectByPrimaryKey(bizType.getBizId());
		if (!oldBizType.getBizName().equals(bizType.getBizName())) {
			ProcDef procDef = new ProcDef();
			procDef.setBizName(bizType.getBizName());
			Example example = new Example(ProcDef.class);
			Example.Criteria criteria = example.createCriteria();
			criteria.andEqualTo("bizId", bizType.getBizId());
			procDefMapper.updateByExampleSelective(procDef, example);
		}
		bizTypeMapper.updateByPrimaryKey(bizType);
		return bizType;
	}

	@Override
	public BizType load(long bizId) {
		return bizTypeMapper.selectByPrimaryKey(bizId);
	}

}
